package jsf;

import java.io.Serializable;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import data.SeasonEnum;
import util.SessionUtil;
import ejb.SemestersBeanRemote;
import entity.Semesters;

@RequestScoped
@ManagedBean
public class SemestersController implements Serializable {

	private static final long serialVersionUID = 1L;
	@EJB(lookup="java:global/EnrollmentManagementEAP/EnrollmentManagementEJB/SemestersBean!ejb.SemestersBeanRemote")
	SemestersBeanRemote bean;
	private Long selectedId;
	private ArrayList<Semesters> semesters = new ArrayList<Semesters>();
	private Semesters semester = new Semesters();
	private ArrayList<SeasonEnum> seasons = new ArrayList<SeasonEnum>();
	
	
	public SemestersController() {
		SessionUtil.authenticate();
	}
	
	public ArrayList<Semesters> getSemesters() {
		ArrayList<Semesters> semesters = new ArrayList<Semesters>();
		semesters.addAll(bean.getAll());
		this.semesters = semesters;
		return this.semesters;
	}
	
	public ArrayList<SeasonEnum> getSeasonEnum() {
		ArrayList<SeasonEnum> seasons = new ArrayList<SeasonEnum>();
		seasons.add(SeasonEnum.FALL);
		seasons.add(SeasonEnum.SPRING);
		seasons.add(SeasonEnum.SUMMER);
		this.seasons = seasons;
		return this.seasons;
	}
	
	public Semesters getSemester() {
		return semester;
	}
	
	private Long getSelectedId() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        return Long.parseLong(context.getRequestParameterMap().get("selectedId"));
    }
	
	public String edit() {
        selectedId = this.getSelectedId();
        if(selectedId != null) {
            this.semester = this.bean.get(selectedId);
            return "semester.xhtml";
        }
        return "semesters.xhtml";
    }
	
	// For Index Form
	public String create() {
		this.selectedId = null;
        this.semester = new Semesters();
        return "semester.xhtml";
    }
	
	// For Edit Form
	public String doSubmit() {
        if(selectedId == null) {
            return this.doCreate();
        } else {
            return this.doEdit();
        }
    }
	
	// For Edit Form
	public String doEdit() {
        this.bean.update(this.semester);
        return "semesters.xhtml";
    }
    
	// For Edit Form
    public String doCreate() {
    	this.bean.insert(this.semester);
        return "semesters.xhtml";
    }
	
    // For Index Form
	public void doDelete() {
        Long selectedId = this.getSelectedId();
        Semesters selectedSemester = this.bean.get(selectedId);
        if(selectedSemester != null) {
            this.bean.delete(selectedSemester);
        }
    }
}
